package com.sgcc.pda.mdrh.task.monitor

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.utils.observe
import com.sgcc.pda.bluetooth.api.BlueManagerImpl
import com.sgcc.pda.bluetooth.blueinterface.ConnectBlueCallBack
import com.sgcc.pda.bluetooth.bluetoothmanager.BlueManager
import com.sgcc.pda.bluetooth.bluetoothmanager.ClassicBluetoothManager
import com.sgcc.pda.bluetooth.config.Constant
import com.sgcc.pda.bluetooth.utils.BlueDeviceInfoUtil
import com.sgcc.pda.bluetooth.utils.ToolGson
import com.sgcc.pda.mdrh.task.MonitorService
import com.sgcc.pda.mdrh.task.base.*
import com.sgcc.pda.mdrh.task.common_ui.base.gone
import com.sgcc.pda.mdrh.task.common_ui.base.oneClick
import com.sgcc.pda.mdrh.task.common_ui.base.startActivityEx
import com.sgcc.pda.mdrh.task.common_ui.base.visible
import com.sgcc.pda.mdrh.task.common_ui.helper.get
import com.sgcc.pda.mdrh.task.model.PlanData
import com.sgcc.pda.mdrh.task.util.*
import com.sgcc.pda.mdrh.task.util.BluetoothHelper.getAdapter
import com.sgcc.pda.mdrh.task.util.BluetoothHelper.isBluetoothConnected
import com.sgcc.pda.mdrh.task.util.BluetoothHelper.isBluetoothEnable
import com.sgcc.pda.mdrh.task.viewmodel.MainViewModel
import com.sgcc.pda.safe.impl.SafeManager
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_empty.*
import net.idik.lib.slimadapter.SlimAdapter
import java.util.concurrent.TimeUnit

class MainActivity : BaseActivity() {

    private lateinit var mManager: BlueManagerImpl
    private var mService: MonitorService? = null
    private val mBlueState = MutableLiveData(false)
    private var mBlueName = ""

    @SuppressLint("AutoDispose", "CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initTitle(title = "关联作业计划", divider = false)
        initListener()
        bindBlueService()
        checkBluetooth()

        main_refresh.isRefreshing = true
        Completable.timer(1000, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { getData() }
    }

    override fun getViewModel() = get<MainViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        BlueManager.getInstance(this)
            .configBlue(
                this.application,
                1,
                true,
                3
            )
        mManager = BlueManagerImpl()

        empty_hint.text = "暂无相关工作计划信息！"
        main_refresh.refresh { getData() }
        main_list.loadLinear(baseContext, main_refresh)

        mAdapter = SlimAdapter.create()
            .register<PlanData>(R.layout.item_main_list) { data, injector ->

                val index = mList.indexOf(data)
                val isLast = index == mList.size - 1

                injector.text(R.id.item_main_title, data.workNo)
                    .text(R.id.item_main_id, data.planNo)
                    .text(R.id.item_main_name, data.planName)
                    .text(R.id.item_main_content, data.workContent)
                    .text(R.id.item_main_type, data.workTyptName)
                    .text(R.id.item_main_start, data.planBeginDate)
                    .text(R.id.item_main_end, data.planEndDate)
                    .visibility(
                        R.id.item_main_divider,
                        if (isLast) View.VISIBLE else View.GONE
                    )
                    .clicked(R.id.item_main) {
                        if (mBlueState.value!!) {
                            showHintDialog(
                                hint = "蓝牙已连接，您确定要关联该工作计划吗？",
                                onSure = { }
                            )
                        } else {
                            showHintDialog(
                                hint = "检测到您还未连接设备，设备连接后才能进行绑定计划操作，是否现在扫码连接设备并绑定计划？",
                                onSure = { startActivityEx<ScanActivity>() }
                            )
                        }
                    }
            }
            .attachTo(main_list)

        observe("blue_scan") {
            val isDeviceSaved =
                ClassicBluetoothManager
                    .getInstance(this)
                    .isConnectedDevice(it)

            if (!isDeviceSaved) {
                showHintDialog(
                    hint = "扫码连接失败，是否进行蓝牙配对连接？",
                    onSure = { mManager.showBluetoothView(this) }
                )
            } else {
                ClassicBluetoothManager.getInstance(this)
                    .connectMAC(
                        it,
                        object : ConnectBlueCallBack {

                            private var dialog: BaseDialog? = null

                            override fun onStartConnect() {
                                dialog = showConnectDialog()
                            }

                            override fun onConnectSuccess(bluetoothDevice: BluetoothDevice) {
                                dialog?.onSuccess("蓝牙连接成功！")
                                runOnUiThread { mBlueState.value = true }

                                BlueDeviceInfoUtil.getInstance()
                                    .setDeviceInfo(
                                        Constant.BLUE_CLS,
                                        ToolGson.getJsonStr(bluetoothDevice),
                                        Constant.CONNECTED
                                    )
                            }

                            override fun onConnectFail() {
                                dialog?.dismiss()
                                runOnUiThread {
                                    mBlueState.value = false
                                    showToast("蓝牙连接失败！")
                                }
                            }
                        }
                    )
            }
        }
    }

    private fun initListener() {
        mBlueState.observe(this) {
            when (it) {
                true -> {
                    main_hint.setColor(
                        "已连接！设备名称：$mBlueName",
                        "已连接！"
                    )
                }
                else -> {
                    main_hint.setColor(
                        "未连接！请扫码连接设备。",
                        "未连接！",
                        R.color.red
                    )
                }
            }
        }

        setOnBlueConnStatusListener {
            connected {
                runOnUiThread {
                    mBlueState.value = true
                    showToast("蓝牙已连接！")
                }
            }
            disConnected {
                runOnUiThread {
                    mBlueState.value = false
                    showToast("蓝牙连接失败！")
                }
            }
        }

        main_scan.oneClick {
            when {
                !isBluetoothEnable() -> mManager.showBluetoothView(this)
                isBluetoothConnected() -> showToast("蓝牙已连接！")
                else -> startActivityEx<ScanActivity>()
            }
        }
    }

    /**
     * 首次判断蓝牙是否连接
     */
    private fun checkBluetooth() {
        if (isBluetoothConnected()) {
            getProfileProxy {
                onServiceConnected { profile, proxy ->
                    val mDevices = proxy.connectedDevices
                    if (!mDevices.isNullOrEmpty()) {
                        mDevices.forEach {
                            mBlueName = it.name ?: it.address
                            mBlueState.value = true
                        }
                    }

                    getAdapter()!!.closeProfileProxy(profile, proxy)
                }
            }
        } else mBlueState.value = false
    }

    /**
     * 绑定蓝牙发送服务
     */
    private fun bindBlueService() {
        bindService(
            Intent(this, MonitorService::class.java),
            object : ConnectionListener() {
                override fun onServiceConnected(name: ComponentName, iBinder: IBinder) {
                    super.onServiceConnected(name, iBinder)

                    if (iBinder is MonitorService.MonitorBinder) {
                        mService = iBinder.getService()
                    }
                }
            },
            BIND_AUTO_CREATE
        )
    }

    override fun getData(index: Int, isLoading: Boolean) {
        SafeManager.getInstance()
            .getPlanList(
                onSuccess = {
                    mList.clear()
                    mList.addItems(it)
                    mAdapter.updateData(mList)
                },
                onError = { showToast(it) },
                onFinally = {
                    main_refresh.isRefreshing = false
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
    }

    private fun getDevice() {
        getViewModel()
            .commandDevice {
                mService?.observeFrameDevice(it)
            }
    }

}